package com.hckjsec.common.core.redis;

import com.hckjsec.common.enums.NumbereEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class SerialNumberUtils {
    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate cacheTemplate;
    @Autowired
    private static RedisTemplate redisTemplate;

    @PostConstruct
    public void init() {
        redisTemplate = cacheTemplate;
    }


    public static String getSerialNumber(NumbereEnum numbereEnum) {
        LocalDateTime nowLdt = LocalDateTime.now();
        String now = nowLdt.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        Long maxExists = 5L;
        String serialNumber;
        Long currentNumber = 1L;
        ListOperations redisList = redisTemplate.opsForList();
        ValueOperations redisString = redisTemplate.opsForValue();
        String key = numbereEnum.getIdent() + now;
        if (!redisTemplate.hasKey(key)) {
            redisString.increment(key);
            redisList.rightPush(numbereEnum.getIdentList(), key);
            // 清理超期缓存
            if (redisList.size(numbereEnum.getIdentList()) > maxExists) {
                String value = (String) redisList.leftPop(numbereEnum.getIdentList());
                redisTemplate.delete(value);
            }
        }else {
            currentNumber= redisString.increment(key);
        }
        serialNumber = numbereEnum.getKey()+ now + String.format("%0"+numbereEnum.getBit()+"d", currentNumber);
        return serialNumber;
    }
}
